<template>
  <view class="content">

    <view @tap="getaddress" class="addressbutton">
      <view>新增收货地址</view>
      <!-- <view> -->
        <image style="width:44rpx; height:44rpx;" src="../static/image/pagesMine/getadd.png" mode="scaleToFill" />
      <!-- </view> -->
    </view>
    <!-- :class="['addresslist', item.consigneeId === act ? 'borderclass' : '']" 更换颜色 -->
    <view @tap="addchoose(item, index)" class="addresslist" v-for="(item, index) in addresslist"
      :class="['addresslist', item.consigneeId === act ? 'borderclass' : '']" :key="index">
      <view style="display:flex;  color: #333333;">
        <view>{{ item.consigneeName }}</view>
        <view style="margin-left: 18rpx;">{{ item.consigneeTelephone }}</view>
      </view>
      <view style="margin-top:8rpx;">
        {{ item.consigneeAddress.split(' ')[0] + item.consigneeAddress.split(' ')[1] }}
      </view>
      <view
        style="display:flex; align-items:center;border-top:3rpx solid #ccc;margin-top:16rpx;justify-content:space-between;padding-top:22rpx;">
        <view>
          <u-checkbox-group>
            <u-checkbox :value="item.consigneeDefault === 1" shape="circle" active-color="red" :name="item.name">
              <text v-if="item.consigneeDefault == 1">默认地址</text>
              <text style="position:relative;left:-50rpx;padding-left:50rpx;" @tap="defaultaddress(item)"
                v-if="item.consigneeDefault == 0">设为默认地址</text>
            </u-checkbox>
          </u-checkbox-group>
        </view>
        <view style="display:flex; align-items:center;">
          <view style="display:flex; align-items:center; margin-right:32rpx;">
            <image style="height:48rpx;width:48rpx;" src="../static/image/pagesHealth/edit.png" mode="scaleToFill" />
            <text @tap.stop="edit(item, index)">编辑</text>
          </view>
          <view style="display:flex; align-items:center;">
            <image style="height:48rpx;width:48rpx;" src="../static/image/pagesHealth/del.png" mode="scaleToFill" />
            <text @tap.stop="deladdress(item)">删除</text>
          </view>

        </view>
      </view>
    </view>
    <!-- 点击遮罩层 -->
    <view @tap="Mask">
      <u-popup mode="bottom" v-model="onaddress" length="55%">
        <view class="address">
          <view style="display: flex; justify-content:space-between;align-items:center;">
            <u-icon  name="close" color="#333333" size="40" style="opacity: 0;"></u-icon>
            <text>编辑地址</text>
            <u-icon @tap="shutdown" name="close" color="#333333" size="40"></u-icon>
          </view>
          <u-form :model="form" ref="uForm">
            <view style="color:#666666;">联系人</view>
            <view style="background-color:white;border-radius:8rpx;">
              <u-form-item label-width="120" style=" padding:0 24rpx; margin-top:24rpx; " label="姓名" prop="name">
                <u-input placeholder="请输入联系人姓名" v-model="form.name" />
                <u-radio-group v-model="valuesex" @change="radioGroupChange">
                  <u-radio @change="radioChange" v-for="(item, index) in list" :key="index" :name="item.name"
                    :disabled="item.disabled" active-color="red">{{ item.name }}</u-radio>
                </u-radio-group>
              </u-form-item>
              <u-form-item label-width="120" style=" padding:0 24rpx;" label="手机号" prop="iphone">
                <u-input placeholder="请输入联系人手机号" v-model="form.iphone" maxlength="11" />
              </u-form-item>
            </view>

            <view style="margin-top: 32rpx; color:#666666;">收货地址</view>
            <view style="background-color:white; border-radius:8rpx;">
              <u-form-item style=" padding:0 24rpx; margin-top:24rpx;">
                <view style="display:flex; justify-content:space-between;flex:1;" @tap="mapopen">
                  <view style="flex: 1;display:flex;margin-right: 10rpx;">
                    <text v-if="addressData.length < 1">我的位置</text>
                    <text
                      style="margin-left: 10rpx;word-break: break-all;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;overflow: hidden;flex: 1;">{{
                        addressData }}</text>
                  </view>
                  <view>
                    <u-icon name="arrow-right"></u-icon>
                  </view>
                </view>
              </u-form-item>
              <u-form-item label-width="120" style=" padding:0 24rpx; " label="具体地址" prop="title">
                <u-input placeholder="请输入具体地址" v-model="form.title" />
              </u-form-item>
            </view>

          </u-form>
          <view style="display: flex; justify-content: space-between; margin-top:24rpx;">
            <view>设置为默认地址</view>
            <view>
              <u-switch size="32" active-color="red" @change="change" :disabled="defaultChecked"
                v-model="checked"></u-switch>
            </view>
          </view>
          <view class="addyes" @tap="addinfo">
            <text>确认</text>
          </view>
        </view>

      </u-popup>
    </view>
    <view v-if="checkshow" @tap="back" class="addbutton">
      <text>确认</text>
    </view>
    <yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" permissionID="ACCESS_FINE_LOCATION"></yk-authpup>
  </view>
</template>
<script>
import { selectUserAddRessList, insertUserAddRess, updateUserAddRess, deleteUserAddRess } from '@/api/main'
import ykAuthpup from "@/components/yk-authpup/yk-authpup.vue";
import _ from 'lodash';
let that = null
export default {
	components: {
	   ykAuthpup
	},
  data() {
    return {
      list: [
        {
          name: "男士"
        },
        {
          name: "女士"
        }
      ],
      valuesex: "男士",
      addresslist: [],
      act: 0,
      backlist: [],
      form: {
        id: 0,
        name: "",
        iphone: null,
        title: "",
        gender: "男士",
        backchoose: false,
        backpay: true
      },
      rules: {

        name: [
          {
            required: true,
            message: "请输入姓名",
            // 可以单个或者同时写两个触发验证方式
            trigger: "blur,change"
          }
        ],
        title: [
          {
            required: true,
            min: 1,
            message: "请输入地址",
            trigger: "change"
          }
        ],
        iphone: [
          {
            type: "number",
            required: true,
            message: "请输入手机号",
            trigger: ["change", "blur"]
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            maxlength: 11,
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"]
          }
        ],
        // ress:[
        //   {
        //     required: true,
        //     message: "请选择",
        //     // 可以单个或者同时写两个触发验证方式
        //     trigger: "blur,change"
        //   }
        // ]
      },
      onaddress: false,
      valueadd: "",
      valuename: "",
      valueiphone: "",
      type: "text",
      border: false,
      checked: false,
      isEditing: true,
      editIndex: -1,
      addressData: '',
      fValue: [],
      defaultChecked: false,
      //地图选址
      title: 'Hello',
      addressmap: {
        province: '',
        city: '',
        district: '',
        name: '',
        address: '',
        location: '',
      },
      lngmap: '',
      latmap: '',
      consigneeLng: '',
      consigneeLat: '',
      checkshow: true,
    };
  },
  onReady() { },
  onLoad(e) {
    this.act = uni.getStorageSync('consigneeId')
    this.backlist = this.addresslist.filter(item => item.consigneeDefault == this.act)
    console.log(this.act);
    that = this
    if (e.checkshow) {
      this.checkshow = e.checkshow
    }
    console.log('this.checkshow', this.checkshow)
    that.latAndLong = uni.getStorageSync('latAndLong')
    console.log('this.consigneeLng', this.consigneeLng)
    console.log('this.consigneeLat', this.consigneeLat)
    // this.addchoose(this.addresslist[0], 0);
    this.getaddlist()
  },
  beforeDestroy() {
    console.log('移除')
    uni.$off();
  },
  onShow() {
    let _this = this;
  },
  watch: {
    checkshow: {
      deep: true,
      handler(newVal, oldVal) {
        if (newVal != true) {
          console.log('111111111111111111111111111111111')
          this.checkshow = false
        }
      },
    },
    onaddress(newValue, oldValue) {      
      let _this = this;
      if(newValue == false) {
        _this.form = {
          id: "",
          location: "",
          title: "",
          gender: "男士",
          name: "",
          iphone: ""
        };
        _this.valuesex = '男士'
      }
    }

  },
  onUnload() {
    // 当页面销毁时需要把该方法销毁
    uni.$off("nextStep");
  },
  methods: {
    //获取地址列表接口
    getaddlist() {
      selectUserAddRessList().then(res => {
        this.addresslist = res.data
        if (uni.getStorageSync('consigneeId')) {
          this.backlist = this.addresslist.filter(item => item.consigneeId == this.act)
          console.log('this.backlist', this.backlist)
        } else {
          this.backlist = this.addresslist.filter(item => item.consigneeDefault == 1)
          console.log('this.backlist', this.backlist)
        }
        console.log('获取地址列表', this.addresslist)
        this.onaddress = false;
        this.form = {
          id: "",
          location: "",
          title: "",
          gender: "男士",
          name: "",
          iphone: ""
        };
      })
    },
    changeAuth(){
      //这里是权限通过后执行自己的代码逻辑
      console.log('权限已授权，可执行自己的代码逻辑了');
      uni.navigateTo({
        url: '/pagesMine/map'
      });
    },
    //去地图选址
    mapopen() {
      this.$refs['authpup'].open()
      if (uni.getStorageSync('platform') === 'android') { // 判断平台
        var context = plus.android.importClass("android.content.Context");
        var locationManager = plus.android.importClass("android.location.LocationManager");
        var main = plus.android.runtimeMainActivity();
        var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
          console.log('gps未开启');
          uni.showModal({
            title: '提示',
            content: '请打开定位服务功能',
            showCancel: false, // 不显示取消按钮
            success() {
              var Intent = plus.android.importClass('android.content.Intent');
              var Settings = plus.android.importClass('android.provider.Settings');
              var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
              main.startActivity(intent); // 打开系统设置GPS服务页面
            }
          });
          return false
        } else {
          console.log('gps已开启');
          uni.$once('commitCheck', (data) => {
            console.log(data, '地址+++1')
            this.addressmap = data
            this.addressData = (data.province ? data.province : '') + (data.city ? data.city : '') + (data.district ? data.district : '') + data.name + (data.addressmap && (Array.isArray(data.addressmap)) ? data.addressmap : '')
            this.latmap = data.location.split(',')[1]
            console.log('看看latmap', this.latmap)
            this.lngmap = data.location.split(',')[0]
            console.log('看看lngmap', this.lngmap)
          });
          
          return true
        }
      } else if (uni.getStorageSync('platform') === 'ios') {
        var cllocationManger = plus.ios.import('CLLocationManager');
        var enable = cllocationManger.locationServicesEnabled();
        var status = cllocationManger.authorizationStatus();
        plus.ios.deleteObject(cllocationManger);
        if (enable && status != 2) {
          console.log('手机系统的定位已经打开');
          // uni.getLocation({
          //   type: "gcj02", // 返回可以用于uni.openLocation的经纬度
          //   success: async (res) => {
          //     console.log('经纬度', res);
          //     console.log('gps已开启');
              uni.$once('commitCheck', (data) => {
                console.log(data, '地址+++1')
                this.addressmap = data
                this.addressData = (data.province ? data.province : '') + (data.city ? data.city : '') + (data.district ? data.district : '') + data.name + (data.addressmap && (Array.isArray(data.addressmap)) ? data.addressmap : '')
                this.latmap = data.location.split(',')[1]
                console.log('看看latmap', this.latmap)
                this.lngmap = data.location.split(',')[0]
                console.log('看看lngmap', this.lngmap)
              });
              uni.navigateTo({
                url: '/pagesMine/map'
              });
            //   try {
            //     // 自己的逻辑代码(调接口)
            //   } catch (err) {
            //     console.log('err', err);
            //   }
            // },
          // });
          return true
        } else {
          console.log('手机系统的定位没有打开');
          uni.showModal({
            title: '提示',
            content: '请打开定位服务功能',
            showCancel: false, // 不显示取消按钮
            success() {
              var UIApplication = plus.ios.import('UIApplication');
              var application2 = UIApplication.sharedApplication();
              var NSURL2 = plus.ios.import('NSURL');
              // var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
              // var setting2 = NSURL2.URLWithString("App-Prefs:root=LOCATION_SERVICES");
              // var setting2 = NSURL2.URLWithString("app-settings");
              var setting2 = NSURL2.URLWithString('App-Prefs:root=Privacy&path=LOCATION');
              // var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION_SERVICES");
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            }
          });
          return false
        }
      }
    },
    chooseAddr() {
      this.$refs['addr'].popUp()
    },
    getaddress() {
      this.addressData = ''
      this.checked = false
      this.isEditing = true;
      this.onaddress = true;
      this.defaultChecked = false
      this.$nextTick(() => {
        this.$refs.uForm.setRules(this.rules);
      });
    },
    back() {
      if (this.addresslist.length > 0) {
        uni.$emit("nextStep", this.backlist);
        uni.navigateBack({
          delta: 1
        });
      } else {
        uni.showToast({
          title: '请添加地址',
          icon: 'none'
        })
      }
    },
    defaultaddress(item) {
      console.log('11111', item)
      let obj = {
        consigneeId: item.consigneeId,
        consigneeDefault: 1
      }
      updateUserAddRess(obj).then(res => {
        console.log('看看默认', res)
        this.getaddlist()
      })
    },
    addchoose(item, index) {
      this.backlist = [];
      console.log(item);
      this.act = item.consigneeId;
      uni.setStorageSync('consigneeId', item.consigneeId);
      // 找到当前选中的 item 在 addresslist 数组中的索引
      this.backlist.push(item);
      console.log('看看数据', this.backlist);
      // uni.setStorageSync('address', this.backlist)
    },
    radioChange(e) {
      console.log('我看看这是什么东西', e);
      console.log('我看看这个', this.valuesex)
      this.form.gender = e;
    },
    // 选中任一radio时，由radio-group触发
    radioGroupChange(e) {
      console.log('我看看这是什么东西', e);
    },
    //新增地址接口
    addaddress() {
      console.log('新增地址默认', this.addressmap)
      console.log('设置默认地址', this.form)
      let obj = {
        consigneeAddress: this.addressmap.name + ' ' + this.form.title,
        consigneeDefault: this.checked ? 1 : 0,
        consigneeDel: 1,
        consigneeId: 0,
        consigneeLat: this.latmap,
        consigneeLng: this.lngmap,
        consigneeName: this.form.name,
        consigneeSex: this.form.gender,
        consigneeTelephone: this.form.iphone,

      }
      insertUserAddRess(obj).then(res => {
        console.log('添加地址', res)
        this.getaddlist()
      })
    },
    //修改地址接口
    upaddress() {
      console.log('编辑地址默认', this.defaultChecked)
      let obj = {
        consigneeAddress: this.addressData + ' ' + this.form.title,
        consigneeDefault: this.checked ? 1 : 0,
        consigneeDel: 1,
        consigneeId: this.form.id,
        consigneeLat: this.latmap ? this.latmap : this.consigneeLat,
        consigneeLng: this.lngmap ? this.lngmap : this.consigneeLng,
        consigneeName: this.form.name,
        consigneeSex: this.form.gender,
        consigneeTelephone: this.form.iphone
      }
      updateUserAddRess(obj).then(res => {
        console.log('修改地址', res)
        this.getaddlist()
      })
    },
    //调接口的确认按钮 编辑和添加是一个按钮
    // addinfo() {
    //   this.$refs.uForm.validate(valid => {
    //     if (valid) {
    //       //看看是编辑还是添加
    //       if (this.addressData) {
    //         if (this.isEditing === true) {
    //           console.log('this.checked', this.checked)
    //           if (this.checked) {
    //             this.addresslist.forEach(address => {
    //               address.backchoose = false;
    //             });
    //           }
    //           this.addaddress()

    //         } else {
    //           if (this.checked) {
    //             this.addresslist.forEach(address => {
    //               address.backchoose = false;

    //             });
    //           }
    //           // 遍历 addresslist 数组，找到需要编辑的数据，并更新它的值
    //           this.addresslist.forEach((item, index) => {
    //             if (item.id === this.form.id) {
    //               item.location = this.form.location;
    //               item.title = this.form.title;
    //               item.gender = this.form.gender;
    //               item.name = this.form.name;
    //               item.iphone = this.form.iphone;
    //               item.backchoose = this.checked;
    //             }
    //           });
    //           this.upaddress()
    //           // this.isEditing = true;
    //           // 将 isEditing 设置为 false，清空表单数据
    //           this.onaddress = false;
    //           this.form = {
    //             id: "",
    //             location: "",
    //             title: "",
    //             gender: "",
    //             name: "",
    //             iphone: ""
    //           };
    //         }
    //       } else {
    //         uni.showToast({
    //           title: '请选择您的位置',
    //           icon: 'none'
    //         })
    //       }

    //     } else {
    //       console.log("验证失败");
    //     }
    //   });
    // },
    addinfo: _.throttle(function () {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          //看看是编辑还是添加
          if (this.addressData) {
            if (this.isEditing === true) {
              console.log('this.checked', this.checked)
              if (this.checked) {
                this.addresslist.forEach(address => {
                  address.backchoose = false;
                });
              }
              this.addaddress()

            } else {
              if (this.checked) {
                this.addresslist.forEach(address => {
                  address.backchoose = false;
                });
              }
              // 遍历 addresslist 数组，找到需要编辑的数据，并更新它的值
              this.addresslist.forEach((item, index) => {
                if (item.id === this.form.id) {
                  item.location = this.form.location;
                  item.title = this.form.title;
                  item.gender = this.form.gender;
                  item.name = this.form.name;
                  item.iphone = this.form.iphone;
                  item.backchoose = this.checked;
                }
              });
              this.upaddress()
              // this.isEditing = true;
              // 将 isEditing 设置为 false，清空表单数据
              this.onaddress = false;
              this.form = {
                id: "",
                location: "",
                title: "",
                gender: "",
                name: "",
                iphone: ""
              };
            }
          } else {
            uni.showToast({
              title: '请选择您的位置',
              icon: 'none'
            })
          }

        } else {
          console.log("验证失败");
        }
      });
    }, 1000),
    change(status) {

      this.checked = status;
    },
    edit(item, index) {
      console.log('看看代码item', item)
      this.consigneeLat = item.consigneeLat
      this.consigneeLng = item.consigneeLng
      this.editIndex = index
      this.form = {
        location: item.consigneeAddress.split(' ')[0],
        title: item.consigneeAddress.split(' ')[1],
        gender: item.consigneeSex,
        name: item.consigneeName,
        iphone: item.consigneeTelephone,
        id: item.consigneeId
      };
      this.valuesex = item.consigneeSex
      this.addressData = item.consigneeAddress.split(' ')[0]
      console.log('this.addressData', this.addressData)
      // this.form.title = item.consigneeAddress.split(';')[1]
      console.log('item.backchoose', item.backchoose)

      this.isEditing = false;
      this.onaddress = true;
      if (item.consigneeDefault == 1) {
        this.checked = true
        this.defaultChecked = true
      } else {
        this.checked = false
        this.defaultChecked = false
      }
      // this.addresslist.forEach((e, eIndex) => {
      //   if (e.consigneeDefault==1 && eIndex === index) {
      //     console.log(eIndex, index)
      //     this.checked = true
      //   }
      // })
      this.$nextTick(() => {
        this.$refs.uForm.setRules(this.rules);
      });
    },
    deladdress(item) {
      let obj = {
        consigneeId: item.consigneeId
      }
      let _this = this;
      uni.showModal({
        title: '删除',
        content: '确认删除嘛！',
        success: function (res) {
          if (res.confirm) {
            deleteUserAddRess(obj).then(res => {
              console.log('删除数据', res)
              _this.getaddlist()
            })
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });

    },
    // 点击遮罩层
    Mask() {
      this.form = {
        id: "",
        location: "",
        title: "",
        gender: "",
        name: "",
        iphone: ""
      };
      this.addressData = ''
      this.addressmap = {
        province: '',
        city: '',
        district: '',
        name: '',
        address: '',
        location: '',
      }
    },
    shutdown() {
      console.log('111')
      this.onaddress = false;
    }
  }
};
</script>

<style scoped lang="scss">
.content {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 30rpx;

  .addresslist {
    align-items: center;
    border-radius: 8rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    background-color: white;
    padding: 32rpx;
    margin-top: 32rpx;
    color: #666666;

    image {
      width: 60rpx;
      height: 30rpx;
    }
  }

  .addbutton {
    /* position: fixed; */
    /* top: 90%; */
    margin-top: 25rpx;
    width: 686rpx;
    height: 96rpx;
    text-align: center;
    line-height: 96rpx;
    background-color: #d12c25;
    border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
    color: white;

  }

  .addressbutton {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 8rpx;
    padding: 26rpx 24rpx 30rpx 34rpx;
    background-color: white;
    font-size: 28rpx;
    color: #666666;

  }

  .borderclass {
    border: 1rpx solid #d12c25;
  }

  .address {

    padding: 32rpx 56rpx 0 56rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: #000000;
    margin-left: 0 24rpx;
    background-color: #F5F5F5;
    height: 100%;
  }

  .addyes {
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
    width: 100%;
    height: 96rpx;
    background-color: #d12c25;
    margin: 44rpx 0 56rpx 0;
  }
}
</style>
